package com.nys.conci.base.utilitario.logger;

import java.sql.Connection;
import java.sql.SQLException;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;
import org.apache.log4j.jdbc.JDBCAppender;
import org.apache.log4j.spi.ErrorCode;

/**
 * Appender basado en JDBCAppender para utilizar JNDI
 * El código fue tomando de: 
 * https://gist.github.com/815351
 * http://j2stuff.blogspot.com/2010/05/log4j-jdbc-with-datasource.html
 * http://www.biskinler.com/en/java/76-web-development/335-java-log4j-jndi-pool-appender.html
 *
 * @author Herman Alonso Barrantes Viquez
 * @version 1.0.0
 * @since 2011-10-01
 *
 */
public class JNDIAppender extends JDBCAppender{
    private String jndiDataSource;

    /** {@inheritDoc} */
    @Override
    protected Connection getConnection() throws SQLException {
        if (jndiDataSource == null) {
            return super.getConnection();
        } else {
            Connection con = lookupDataSource().getConnection();
            return con;
        }
    }

    /**
     * Looks up the datasource in the naming context specified by the
     * {@link #jndiDataSource}.
     *
     * @return the datasource.
     */
    private DataSource lookupDataSource() {
        try {
            Context context = new InitialContext();
            return (DataSource) context.lookup(jndiDataSource);
        } catch (NamingException e) {
            throw new RuntimeException("Cannot find JNDI DataSource: " + jndiDataSource, e);
        }
    }

    /** {@inheritDoc} */
    @Override
    protected void closeConnection(Connection con) {
        try {
            con.close();
        } catch (SQLException e) {
            errorHandler.error("Failed to close connection", e, ErrorCode.CLOSE_FAILURE);
        }
    }

    public String getJndiDataSource() {
        return jndiDataSource;
    }

    public void setJndiDataSource(String jndiDataSource) {
        this.jndiDataSource = jndiDataSource;
    }
}
